import { create } from 'zustand';
import { QuestionTitlePropsType } from '../components/quesitonComponents/questionTitle/interface';
import { QuestionInputPropsType } from '../components/quesitonComponents/questionInput/interface';
import { QuestionParagraphPropsType } from '../components/quesitonComponents/questionParagraph/interface';
import { QuestionInfoPropsType } from '../components/quesitonComponents/questionInfo/interface';
import { QuestionRadioPropsType } from '../components/quesitonComponents/questionRadio/interface';
import { QuestionTextareaPropsType } from '../components/quesitonComponents/questionTextarea/interface';
import { persist, createJSONStorage } from 'zustand/middleware';
import _ from 'lodash';
import { v4 as uuidv4 } from 'uuid';
import { arrayMove } from '@dnd-kit/sortable';
export type ComponentPropsType =
  | QuestionTitlePropsType
  | QuestionInputPropsType
  | QuestionParagraphPropsType
  | QuestionInfoPropsType
  | QuestionRadioPropsType
  | QuestionTextareaPropsType;
export type ComponentInfoType = {
  id: string; //TODO
  type: string;
  title: string;
  isHidden?: boolean;
  isLocked?: boolean;
  props: ComponentPropsType;
};
export type ComponentsStateType = {
  components: ComponentInfoType[];
  selectedId: string;
  copiedComponent: ComponentInfoType | null;
  resetComponents: (components: ComponentInfoType[]) => void;
  changeSelectedId: (selectedId: string) => void;
  addComponents: (component: ComponentInfoType) => void;
  setComponents: (value: Record<string, any>) => void;
  hideOrShowSelectedComponent: (selectedId: string) => void;
  hideOrShowSelectedComponentOnLayers: (selectedId: string) => void;
  LockorUnlockSelectedComponent: (selectedId: string) => void;
  copySelectedComponent: (selectedId: string) => void;
  PasteSelectedComponent: () => void;
  selectPrevComponent: () => void;
  selectNextComponent: () => void;
  removeSelectedComponent: (selectedId: string) => void;
  setComponentInfo: (value: Record<string, any>) => void;
  moveComponent: (oldIndex: number, newIndex: number) => void;
};
const questionStore = create(
  persist<ComponentsStateType>(
    (set, get) => ({
      selectedId: '',
      components: [],
      copiedComponent: null,
      //修改selectedId
      changeSelectedId(selectedId: string) {
        set({ selectedId });
      },
      //根据选择位置添加组件
      addComponents(component) {
        set((state) => {
          if (state.selectedId) {
            const idx = state.components.findIndex((c) => c.id === state.selectedId);
            if (idx !== -1) {
              const _components = JSON.parse(JSON.stringify(state.components));
              _components.splice(idx + 1, 0, component);
              return {
                components: _components,
              };
            }
          }
          return { components: [...state.components, component] };
        });
      },
      //修改组件信息
      setComponentInfo(value) {
        const idx = get().components.findIndex((c) => c.id === get().selectedId);
        const _components = JSON.parse(JSON.stringify(get().components));
        _components[idx] = { ..._components[idx], ...value };
        set({ components: _components });
      },
      //修改属性更改组件信息 prop
      setComponents(value) {
        //找到组件列表对应的组件
        const idx = get().components.findIndex((c) => c.id === get().selectedId);
        console.log(get().components[idx]);
        const _components = JSON.parse(JSON.stringify(get().components));
        _components[idx] = {
          ..._components[idx],
          props: { ..._components[idx].props, ...value },
        };
        //修改这个组建中props的值
        set({ components: _components });
      },
      //删除选中的组件
      removeSelectedComponent(selectedId) {
        console.log(selectedId);
        if (!selectedId) return;
        const _components = _.cloneDeep(get().components).filter((_c) => !_c.isHidden);
        const idx = _components.findIndex((c) => c.id === selectedId);
        _components.splice(idx, 1);
        set({ components: _components });
        set({
          selectedId: (get().components[idx - 1]?.id ? get().components[idx - 1]?.id : get().components[0]?.id) || '',
        });
      },
      //隐藏/显示选中的组件
      hideOrShowSelectedComponent(selectedId) {
        console.log(selectedId);
        const _components = _.cloneDeep(get().components);
        const idx = _components.findIndex((c) => c.id === selectedId);
        if (idx == -1) return;
        _components[idx].isHidden = !_components[idx].isHidden;
        set({ components: _components });
        set({
          selectedId: _components[idx].isHidden
            ? (get().components.filter((c) => !c.isHidden)[idx - 1]?.id
                ? get().components.filter((c) => !c.isHidden)[idx - 1]?.id
                : get().components.filter((c) => !c.isHidden)[0]?.id) || ''
            : selectedId,
        });
      },
      //根据layerst图层隐藏/显示选中的组件
      hideOrShowSelectedComponentOnLayers(selectedId) {
        const _components = _.cloneDeep(get().components);
        const idx = _components.findIndex((c) => c.id === selectedId);
        if (idx == -1) return;
        _components[idx].isHidden = !_components[idx].isHidden;
        set({ components: _components });
      },
      //锁定/解锁选中的组件
      LockorUnlockSelectedComponent(selectedId) {
        const _components = _.cloneDeep(get().components);
        const idx = _components.findIndex((c) => c.id === selectedId);
        if (idx == -1) return;
        _components[idx].isLocked = !_components[idx].isLocked;
        set({ components: _components });
      },
      //拷贝当前选中的组件
      copySelectedComponent(selectedId) {
        const component = get().components.find((c) => c.id === selectedId);
        if (!component) return;
        const newComponent = _.cloneDeep(component);
        set({ copiedComponent: newComponent });
      },
      //粘贴组件
      PasteSelectedComponent() {
        if (!get().copiedComponent) return;
        const newComponent = _.cloneDeep(get().copiedComponent)!;
        newComponent.id = uuidv4();
        const _components = _.cloneDeep(get().components);
        const selectedId = get().selectedId;
        const idx = _components.findIndex((c) => c.id === selectedId);
        if (idx == -1) {
          _components.push(newComponent);
        } else {
          _components.splice(idx + 1, 0, newComponent);
        }
        set({ components: _components });
        set({
          selectedId: newComponent.id,
        });
      },
      //选中上一个
      selectPrevComponent() {
        const selectedId = get().selectedId;
        const components = get().components.filter((c) => !c.isHidden);
        const idx = components.findIndex((c) => c.id === selectedId);
        if (idx == -1) return;
        const newIdx = idx - 1;
        if (newIdx < 0) return;
        set({ selectedId: components[newIdx].id });
      },
      //选中下一个
      selectNextComponent() {
        const selectedId = get().selectedId;
        const components = get().components.filter((c) => !c.isHidden);
        const idx = components.findIndex((c) => c.id === selectedId);
        if (idx == -1) return;
        const newIdx = idx + 1;
        if (newIdx >= components.length) return;
        set({ selectedId: components[newIdx].id });
      },
      //移动组件位置
      moveComponent(oldIndex: number, newIndex: number) {
        const newarr = arrayMove(get().components, oldIndex, newIndex);
        set({ components: newarr });
      },
      //初始化组件
      resetComponents(components) {
        set({ components });
      },
    }),
    {
      name: 'questionStorage',
      storage: createJSONStorage(() => localStorage), // 选择存储方式 这里要用createJSONStorage而不是window
    },
  ),
);

export default questionStore;
